﻿namespace BM.Tools.WebControls.MForm.Controls.Helper
{
    using System.Web.UI.WebControls;
    using System.Xml.XPath;

    /// <summary>
    /// A helper class for retrieving xpath navigable data source.
    /// </summary>
    public static class NavigableDataBoundControlHelper
    {
        /// <summary>
        /// Gets either the data source property or the xml from the data source object.
        /// </summary>
        /// <param name="control">
        /// The control.
        /// </param>
        /// <returns>
        /// the navigable object.
        /// </returns>
        public static IXPathNavigable GetDataSource(this BaseDataBoundControl control)
        {
            var dataSource = control.DataSource;
            if (dataSource != null)
            {
                return dataSource as IXPathNavigable;
            }

            var dataSourceObject = control.GetDataSourceObject();
            return dataSourceObject != null ? dataSourceObject.GetXmlDocument() : null;
        }

        /// <summary>
        /// Gets the xml data source object.
        /// </summary>
        /// <param name="control">
        /// The control.
        /// </param>
        /// <returns>
        /// The data source object.
        /// </returns>
        public static XmlDataSource GetDataSourceObject(this BaseDataBoundControl control)
        {
            return control.NamingContainer.FindControl(control.DataSourceID) as XmlDataSource;            
        }
    }
}
